package org.hales.security;

import org.hales.common.Enum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.hales.common.ServerResponse;
import org.hales.manager.RequestManager;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component("smsCodeFilter")
public class CaptchaFilter extends OncePerRequestFilter {




    @SneakyThrows
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
            // 获取前端提交的验证码参数
            String code = request.getParameter("captcha");
            // 从 Session 中获取存储的正确验证码
            String captcha = (String) request.getSession().getAttribute("captcha");

            // 获取当前请求的路径
            String requestURI = request.getRequestURI();

            // 如果当前请求是登录请求，则需要校验验证码
            if (requestURI.endsWith("/user/login.do")||requestURI.endsWith("/user/securityLogin.do") ) {
                // 如果没有填写验证码，或者验证码为空，则重定向到首页（或登录页，可根据实际业务调整）
                Enum.ValidCheckCodeResultType validCheckCodeResultType = RequestManager.validCheckCode(code);
              switch (validCheckCodeResultType)
              {
                  case Success:
                      // 如果验证码校验通过，则继续执行过滤链（后续会执行用户名密码认证等流程）
                      filterChain.doFilter(request, response);
                      break;
                  default:
                      returnJson(response, Enum.ResponseCode.ERROR.getCode(), validCheckCodeResultType.getDesc());
                      return;
              }
            }
            else {
                // 非登录请求直接放行
                filterChain.doFilter(request, response);
            }

    }


    private void returnJson(HttpServletResponse response,int code, String jsonString) throws Exception {

        Object obj = ServerResponse.createByErrorCodeMessage(code, jsonString);
        ObjectMapper objMapper = new ObjectMapper();
        String result = objMapper.writeValueAsString(obj);
        response.setContentType("application/json; charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(result);
        writer.close();
        response.flushBuffer();
    }
}
